<template>
  <div class="container pisa">
    <div class="text-center upload-box">
      <div class="upload-file">
        <el-upload ref="rebateUpload"
          class="upload-demo" 
          drag
          :action="upload" name="excel" :limit="1"
          :before-upload="beforeUpload"
          :headers="headerUpload"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :show-file-list="false"
          :on-error="handleError"
          :on-progress="uploadProcess"
          v-show="isShowUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{$t('page.drop')}}，
            <em>{{$t('page.click')}}</em>
          </div>
        </el-upload>
        <div class="upload-name-box" v-show="isShowUploadtxt">
          <el-progress
            :percentage="retunProces(percentage)"
            :color="customColor"
            v-show="isShowPer">
          </el-progress>
          <div class="upload-name">
            {{uploadFile.name}}
            <span @click="handleRemove">x</span>
          </div>
          <div class="reset-back" v-if="editText">
            <div
              class="link"
              @click="changLogData">
              {{$t('page.modData')}}
            </div>
            <span class="link"
              @click="handleRemove">{{$t('page.emptyData')}}
            </span>
          </div>
        </div>
      </div>
    </div>
    <!-- 上传done -->

    <div class="container-body"
      v-show="isShowLog">
      <!-- <div style="width:60%;float:left;">
        <img :src="stepOneList.img" alt=""
          style="margin-bottom:30px;width:100%;" />
      </div> -->

      <div
        style="padding-left:50px">
        <div style="text-align:right;">
          <el-button type="text"
            @click="downloadExl()" size="mini">
            {{$t('page.exportTable')}}</el-button>
        </div>
        <!-- <table id="table-2" width="100%">
          <tr>
            <td width="50%">
              {{$t('page.formula')}}
            </td>
            <td>
              <span >{{ stepOneList.formula }}</span>
                <br/>
            </td>
          </tr>
          <tr
            v-if="stepOneList.struct && stepOneList.struct.rsquare">
            <td width="50%">
              {{$t('page.Rsquare')}}
            </td>
            <td>
              {{stepOneList.struct.rsquare}}
            </td>
          </tr>
          <tr v-if="stepOneList.params">
            <td width="50%">
              {{$t('page.parameter')}}</td>
            <td>
              <template
                v-for="(value, key, index) in stepOneList.params">
                  <p class="data-item">{{key}}：{{value}} <br /> </p>
              </template>
            </td>
          </tr>

          <tr v-if="!stepOneList.exportConcentration">
            <td width="50%">
              {{$t('page.ConcentrationValue')}}
            </td>
            <td>
              <template
                v-for="(value, key) in stepOneList.ndResult">
                <p class="data-item">
                  {{key}}：{{value}}
                  <br>
                </p>
              </template>
            </td>
          </tr>
        </table> -->
      </div>
      <!-- 96孔 -->
      <div style="padding-left:40px;">
        <h4>0表示阴性 1表示阳性</h4>
        <holesTable 
          v-if="stepOneList.result_np"
          :yinYangHole="true"
          :exportConcentration="stepOneList.result_np">
        </holesTable>

        <histogram
          v-if="stepOneList.result_data"
          :data="stepOneList.result_data || {}"
          :yinYang="stepOneList.result_np"
          :cutoffValue="stepOneList.cutoff"
        ></histogram>
      </div>
    </div>

    <!-- 提交弹窗 -->
    <el-dialog :visible="isShowStepOne"
      :close-on-click-modal="false"
      :show-close="false" :destroy-on-close="true"
      width="80%">
      <el-form 
        label-position="right"
        label-width="80px">
        <el-form-item :label="$t('page.unit')">
          <el-radio
            v-for="(item, index) in unitList"
            :key="index" 
            v-model="unit"
            :label="item">{{item}}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('page.testMethod')">
          <el-radio v-model="dialogForm.testMethod" label="1">{{ $t('page.Sandwich') }}</el-radio>
          <el-radio v-model="dialogForm.testMethod" label="2">{{ $t('page.competitionLaw') }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('page.computedMethod')">
          <el-radio v-model="dialogForm.computedMethod" label="1">{{ $t('page.ratio') }}</el-radio>
          <el-radio v-model="dialogForm.computedMethod" label="2">{{ $t('page.percentage') }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('page.cutoffCoefficient')">
          <el-input type="input" v-model="dialogForm.cutoffValue"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('page.negativeControl')">
              <el-select multiple v-model="dialogForm.negativeValue">
                <el-option
                  v-for="item in data.odname"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('page.positiveControl')">
              <el-select multiple v-model="dialogForm.positiveValue">
                <el-option
                  v-for="item in data.odname"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item :label="$t('page.label')">
          <holesTable 
            :noDisabled="data.odname"
            :clear.sync="clear"
            @inputHoles="inputHoles"
          ></holesTable>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlerClose">
          {{$t('page.cancel')}}</el-button>
        <el-button type="primary"
          :loading="btnLoading" @click="submit">
          {{$t('public.comfirmText')}}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import easyChart from "@/components/EasyChart";
import { receiveStep2 } from "@/api/table";
import { setStore, getStore } from "@/utils/common";
import { getToken } from "@/utils/auth";
import holesTable from "@/components/96HolesTable";
import histogram from '../components/histogram.vue'


export default {
  data() {
    return {
      stepOneList: {
        params: {},
        struct: {},
        ng: [],
        x: "",
        histogram: {}
      },
      dialogForm: {
        negativeValue: '',
        positiveValue: '',
        cutoffValue: '', // 弹窗cutoff值
        testMethod: '1',
        computedMethod: '1'
      },
      unitList: ["mg/ml", "pg/ml", "ng/ml", "μg/ml", 'gc/ml'],
      concentration: [], // 输入的浓度
      keyList: [], // 数据的key
      isShowLog: false, //是否结果页面
      isShowStepOne: false, //是否显示弹窗
      isShowUpload: true, // 上传组件
      isShowUploadtxt: false, // 文件名
      uploadFile: {}, // 上传的文件
      exlName: "", // 下载表格名
      isShowPer: false, // 进度条
      percentage: 0, // 进度条数值
      customColor: "#e6a23c",
      unit: "μg/ml", // 单位
      data: {
        odname: []
      }, // 文件上传返回的数据
      btnLoading: false, // 按钮loading
      editText: false, // 兼容老页面不展示修改数据按钮
      clear: false, //清空数据
    };
  },
  components: {
    // easyChart,
    holesTable,
    histogram,
  },
  methods: {
    initData() {},
    changLogData() {
      this.isShowStepOne = true
      // this.clear = true
    },
    goNext(route, type) {
      if (type === 1) {
        setStore("chartData", this.lightRate);
      }
      this.$router.push({ path: route });
    },

    inputHoles(value, keyList) {
      this.keyList = keyList
      this.concentration = value;
    },

    // 关闭弹窗
    handlerClose() {
      this.isShowStepOne = false;
      this.concentration = [];
    },

    // 弹窗提交信息
    async submit() {
      this.btnLoading = true;
      const requestList = []
      this.keyList.forEach((item, index) => {
        requestList.push(`${item}:${this.concentration[index]}`)
      })
      // const negativeList = []
      // this.dialogForm.negativeValue.forEach(sub => {
      //   this.keyList.forEach((item, index) => {
      //     if(item === sub) {
      //       negativeList.push(`${item}:${this.concentration[index]}`)
      //     }
      //   })
      // })
      // const positiveList = []
      // this.dialogForm.positiveValue.forEach(sub => {
      //   this.keyList.forEach((item, index) => {
      //     if(item === sub) {
      //       positiveList.push(`${item}:${this.concentration[index]}`)
      //     }
      //   })
      // })
      try {
        const res = await receiveStep2({
          uuid: this.exlName,
          unit: this.unit,
          concent: requestList,
          negative_concent: this.dialogForm.negativeValue,
          positive_concent: this.dialogForm.positiveValue,
          cutoff_int: this.dialogForm.cutoffValue,
          way: this.dialogForm.testMethod,
          typeWay: this.dialogForm.computedMethod
        });
        if (res.status === 200) {
          this.isShowStepOne = false;
          this.isShowLog = true;
          this.btnLoading = false;
          this.stepOneList = res.data;
        }
      } catch {
        return (this.btnLoading = false);
      }
    },

    beforeUpload(file) {
      this.uploadFile = file;
      this.isShowPer = true;
      this.isShowUpload = false;
      this.isShowUploadtxt = true;
      this.percentage += 60 + Math.floor(Math.random() * 10);
    },
    uploadProcess(e, file) {
      this.uploadFile = file;
      this.percentage = 100;
    },
    retunProces(num) {
      return Number(num.toFixed(0));
    },
    handleSuccess(file) {
      if (file.status === 200) {
        if (file.data.img) {
          this.stepOneList = file.data;
          this.isShowLog = true;
          this.isShowPer = false;
          return;
        }
        this.editText = true
        this.data = file.data;
        this.isShowPer = false;
        this.isShowStepOne = true;
        this.clear = true
        this.exlName = file.data.uuid;
        setStore('auuid', file.data.uuid)
      } else {
        if (file.status === 502) {
          this.$msgbox
            .confirm(
              "你已被登出，可以取消继续留在该页面，或者重新登录",
              "确定登出",
              {
                confirmButtonText: "重新登录",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
            .then(() => {
              this.$store.dispatch("FedLogOut").then(() => {
                location.reload();
              });
            });
        } else {
          this.$message.error(file.msg);
        }
      }
    },
    handleError() {
      this.$message.error("发生错误请联系管理员");
    },
    handleRemove() {
      this.$refs["rebateUpload"].clearFiles(); //清除文件
      //上传框
      this.isShowUpload = true;
      this.isShowUploadtxt = false;
      // //上传进度条
      this.percentage = 0;
      // //显示进度
      this.isShowPer = false;
      this.stepOneList = {
        params: {},
        struct: {},
        ng: "",
        x: "",
      };
      this.uploadFile = {};
      // this.data = {}
      this.isShowStepOne = false;
      this.isShowLog = false;
      this.editText = false
    },
    downloadExl() {
      if (this.exlName) {
        const lang = getStore("spr-lang");
        const href = `${process.env.BASE_URL}receive/download/excel/1/${lang}/${this.stepOneList.uuid}`;
        window.open(href, "_blank");
      }
    },
  },
  computed: {
    upload: () => {
      return process.env.BASE_URL + "receive/mark/upload/stepA";
    },
    headerUpload: () => {
      const data = {};
      data.TOKEN = getToken();
      if (localStorage.getItem("spr-lang") === "en") {
        data.LANG = "ENG"; // 传语言
      }
      return data;
    },
  },
};
</script>
<style lang="less" scoped>
.pisa {
  ::v-deep {
    .el-form-item__label::before {
      content: '*';
      color: red;
      margin-right: 2px;
    }
    .el-select {
      overflow: hidden;
    }
    .el-progress {
      width: 200px;
    }
  }
  .upload-name-box {
    flex-direction: column;
    .upload-name {
      display: flex;
      align-items: center;
      width: 100%;
      margin: 10px 0;
      span {
        margin-left: 4px;
      }
    }
  }
  .table {
    td {
      min-width: 100px;
    }
  }
  .form-item {
    position: relative;
  }
  .concent {
    position: absolute;
    top: 70px;
    left: 40px;
    font-weight: 700;
  }
  ::v-deep {
    .el-dialog__footer {
      text-align: center;
    }
    .el-form-item__content {
      overflow: auto;
      position: static;
    }
  }
  table {
    width: 100%;
    border-collapse: collapse;
    text-align: center;
    margin-bottom: 20px;
  }
  #table-2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: #000;
  }
  #table-2 tr {
    border: 1px solid #000 !important;
  }

  #table-2 td:first-child {
    border-left: 1px solid #000;
  }

  /* Padding and font style */
  #table-2 td,
  #table-2 th {
    padding: 10px 15px;
    font-size: 12px;
    font-family: Verdana;
    border-right-width: 1px;
    border-right-style: solid;
  }

  .reset-back {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .link {
      white-space: nowrap;
      cursor: pointer;
      color: #409eff;
      font-style: normal;
      margin-right: 20px;
    }
  }

  .data-item {
    text-align: left;
    padding-left: 40px;
  }

  // @media screen and (min-width: 1000px) {
  //   .data-item {
  //     display: inline-block;
  //     margin-right: 20px;
  //   }
  // }
}
</style>